import { lazy } from 'react'
import Excel from '@utils/upload-excel'
import Csv from '@utils/upload-csv'

const { $http, $fn } = window

const Select = lazy(()=>import('@antd/form/select'))
const width = 150
/* -------------------------------------------------------- 上传 json 数据 -- */
export const uploadExcel = opt => {
	let { cols = [], modal={}, param, api='mysql/intofile'} = opt ?? {}
	Excel.open( async data => {
		const colData = await window.$http.pull(null, 'mysql/col', { param, loading:true })
		let no_head = false
		if(Array.isArray(opt?.cols)){
			cols = opt?.cols
			const name = cols.map( (v,i) => {
				v.dataIndex = i
				return i
			})
			for(let v of data){
				Object.keys(v).forEach( (m,i) =>{
					v[name[i]] = v[m]
				})
			}
		}else{
			no_head = data?.[0]?.[0] === 0	// 判断第一条数据的第一个字段 0 是否存在
			let first = {} 	// 获取第一条数据
			// 替换 key
			if( no_head ){
				data = data.map((row, i) =>{
					let stack = {}
					let j = 0
					for(let k in row){
						if(j!==0) {
							let v = row[k] 
							stack['C' + j] = v === '\\N' || v === 'null' ? null : v
						}
						j++
					}
					// 获取第一条数
					if( i === 0 ){
						let k = 0
						for(let v in row){
							if(k!==0) {
								if( v?.includes?.('\\N') ){
									v = null
								}
								first['C' + k] =  '第一行必须有标题'
							}
							k++
						}
					}
					stack['jz_index'] = i
					return stack
				})
				data.unshift(first)
			}else{
				data.forEach( (p, k) =>{
					for(let i in p){
						let v = p[i]
						if(v === '\\N' || v === 'null') p[i] = null
					}
					p['jz_index'] = k
				})
			}
			
			let stack = {}
			let index = 0
			for(let i in data[0]) {
				let p = colData?.[ no_head ? index - 1 : index ]?.col ?? '字段不对应'
				index ++
				stack[i] = null
				cols.push({
					dataIndex:i,  
					title:i,
					width,
					ellipsis:true,
					render:(t,r,k) => k === 0 ? <Select value={t} p={p} data={colData} idStr='col' nameStr='col' className='w' onChange={v=>{
						data[0][i] = v
						window.$tableModalRef().tableRef().setIndexData(data)
					}} /> : t
				})
			}
			data.unshift(stack)
		}
		const col = data[0]
		window.$tableModalRef().open({
			modal:{
				title 	:'导入 — 确认',
				width 	: '98%',
				height	: '80%',
				onOk: ({ close }) => {
					if(no_head) return $fn.msg.error('数据格式错误')
					let rs = []
					data.forEach( (v,i) => {
						if(i!==0){
							let stack = {}
							for(let k in v){
								let name = col[k]
								if( name ){
									stack[name] = v[k]
								}
							}
							if($fn.hasObject(stack)) rs.push(stack)
						}
					})
					if( rs.length > 0 ){
						$http.post(null,api, { param: { data:rs, database:param.database, table_name:param.table_name } }).then(()=>{
							$fn.msg.success("导入数据成功")
							close()
						})
					}else{
						$fn.msg.warning("请选择至少一列对应字段")
					}
				},
				...modal
			},
			table:{ idStr:'jz_index', cols, data, minus:1, max:10000 },
		})
	})
	return true
}
export const uploadCsv = opt =>{
	let { cols = [], modal={}, param, api='mysql/intofile'} = opt ?? {}
	Csv.open( async data => {
		const colData = await window.$http.pull(null,'mysql/col', { param, loading:true })
		const arr = data.split('\n')
		data = []
		if($fn.hasArray( arr )){
			data = arr.map(v =>{
				let s = v.split(',')
				let stack = {}
				s.forEach((v,k)=>{
					if(v.includes('"')){
						v = v.replace(/"/g,'')
					}else{
						let n = Number(v)
						v = isNaN(n) ? null : n
					}
					stack['C' + (k+1)] = v 
				})
				return stack
			})
		}
		data.pop()
		if(Array.isArray(opt?.cols)){
			cols = opt?.cols
			const name = cols.map( (v,i) => {
				v.dataIndex = i
				return i
			})
			for(let v of data){
				Object.keys(v).forEach( (m,i) =>{
					v[name[i]] = v[m] ?? 0
				})
			}
		}else{
			let stack = {}
			let index = 0
			for(let i in data[0]) {
				let p = colData?.[index]?.col ?? '字段不对应'
				index ++
				stack[i] = null
				cols.push({
					dataIndex:i,  
					title:i,
					width,
					ellipsis:true,
					render:(t,r,k) => k === 0 ? <Select p={p} value={t} data={colData} idStr='col' nameStr='col' className='w' onChange={v=>{
						data[0][i] = v
						window.$tableModalRef().tableRef().setIndexData(data)
					}} /> : t
				})
			}
			data.unshift(stack)
		}
		const col = data[0]
		window.$tableModalRef().open({
			modal:{
				title 	:'导入 — 确认',
				width 	: '98%',
				height	: '80%',
				onOk: ({ close }) => {
					let rs = []
					data.forEach( (v,i) => {
						if(i!==0){
							let stack = {}
							for(let k in v){
								let name = col[k]
								if( name ){
									stack[name] = v[k]
								}
							}
							if($fn.hasObject(stack)) rs.push(stack)
						}
					})
					if( rs.length > 0 ){
						$http.post(null,api, { param: { data:rs, database:param.database, table_name:param.table_name } }).then(()=>{
							$fn.msg.success("导入数据成功")
							close()
						})
					}else{
						$fn.msg.warning("请选择至少一列对应字段")
					}
				},
				...modal
			},
			table:{ cols, data, idStr:'C1', minus:1, max:10000 },
		})
	})
	return true
}